package com.financing.controller.user;
import java.io.File;
import java.util.Date;

import com.financing.components.payment.Gateway;
import com.financing.model.Data;
import com.financing.model.system.Address;
import com.financing.model.user.Bank;
import com.financing.model.user.BankCard;
import com.financing.model.user.User;
import com.financing.service.user.BankCardService;
import com.financing.service.user.BankService;
import com.financing.util.AES;
import com.financing.util.CheckIdCard;
import com.financing.util.DateUtil;
import com.financing.util.FileUtil;
import com.financing.util.Json;
import com.financing.util.Str;
import com.financing.util.XmlHelper;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 *  用户银行卡控制器
 * @since 2017-06-06
 * @author 无处不在的二叔
 */
public class BankCardController extends Controller {
	private static BankService bank = new BankService();
	private static BankCardService bankCard = new BankCardService();
	// private static final Logger logger = Logger.getLogger(UserController.class);
	
	/**
	 * 获取用户的主银行卡
	 */
	public void index() throws Exception {
		User u = getAttr("user");
		int aes = getParaToInt("aes",1);
		int userId = getParaToInt("userId", u.getId());

		// 获取银行卡信息
		BankCard bc = bankCard.findMainCard(userId);
		Bank bk = bank.findByCode(bc.getBankCode());
		bc.put("single",String.valueOf(bk.getSingle()));
		bc.put("day",String.valueOf(bk.getDay()));
		bc.put("logo",String.valueOf(bk.getLogo()));
		u.put("amount",String.valueOf(u.getAvailableAmount()));
		
		// 敏感信息处理
		if(aes==1) {
			bc.setMobile(AES.encode(bc.getMobile()));
			bc.setBankAccount(AES.encode(bc.getBankAccount()));
			u.setMobile(AES.encode(u.getMobile()));
			u.setCertNum(AES.encode(u.getCertNum()));
			u.setBankCard(AES.encode(u.getBankCard()));
			u.setEmail(AES.encode(u.getEmail()));
		}
		
		// 预计到款日期
		Date now = new Date();
		int week = DateUtil.getWeek(now);
		String day = DateUtil.adjust(now, week==5 || week==6 || week==7?8-week:1, DateUtil.DATE_DEFAULT_FORMAT);
		
		renderJson(Json.ok("返回银行卡信息成功！",
			Data.put("card",bc,"user",u,"day",day,"summary","提现到账默认为“t+1模式”\n 资金将在提现后的下一个工作日到账，如遇周末和法定节假日，则顺延至下一个工作日到账。")));
	}
	
	/**
	 * 绑定银行卡
	 */ 
	@Before(Tx.class)
	public void bind() throws Exception {
		//http://183.136.136.254/bankCard/bind?token=1f421fb7b00b43b019ab90d59a535328&certNum=330225199111280814&bankAccount=6236681590003409497&accountName=%E8%B0%A2%E5%BF%A0%E5%B1%B1&city=3320&aes=0&bank=0105
		User u = getAttr("user");
		int aes = getParaToInt("aes",1);
		String certNum = getPara("certNum");
		String bankAccount = getPara("bankAccount","");
		String accountName = getPara("accountName");
		Address city = Address.me.findFirst("select * from address where city=?",getPara("city"));
		Bank bank = Bank.me.findFirst("select * from bank where name=?",getPara("bankName"));
		String payPassword = getPara("payPassword");
		
		// 需要AES解密
		if(aes==1) {
			certNum = AES.decode(certNum);
			bankAccount = AES.decode(bankAccount);
			payPassword = AES.decode(payPassword);
		}

		// 检查身份证格式
		if(Str.nb(certNum) && Str.nb(accountName) && Str.nb(payPassword)) {
			CheckIdCard card = new CheckIdCard(certNum);
			if(card.validate()){
				u.setRealName(accountName)
					.setCertNum(certNum)	//身份证号码
					.setBirthday(card.getBirthday())	// 第7~14位数字表示：出生年、月、日
					.setSex(card.isMale()?1:2) // 第17位数字表示性别：奇数表示男性，偶数表示女性； 
					.setBankCard(bankAccount);
				Ret ret = BankCardService.bind(u, city, bank, payPassword);
				renderJson(ret.isOk()?Json.ok("操作成功！"):Json.error(ret.getStr("msg")));
			}else{
				renderJson(Json.error("身份证格式不正确！"));
			} 
		}else{
			renderJson(Json.error("数据不可为空！"));
		} 
	}
	
	/**
	 * 换绑银行卡
	 * @throws Exception 
	 */ 
	public void change() throws Exception {
		User u = getAttr("user");
		File file1 = getFile("file1")!=null ? getFile("file1").getFile() : null;
		File file2 = getFile("file2")!=null ? getFile("file2").getFile() : null;
		String bankAccount = getPara("bankAccount","");
		System.out.println(getPara("bank",""));
		Bank bank = Bank.me.findFirst("select * from bank where name=?",getPara("bank",""));
		Address city = Address.me.findFirst("select * from address where city=?",getPara("city"));
        BankCard bc = bankCard.findByAccount(bankAccount);
        
		if(bc==null || Str.ne("success", bc.getStatus())) {
			String code = DateUtil.getTimeStamp();
			XmlHelper res = Gateway.post("/userChangeCard.action", 
				Data.put(
					"mchnt_txn_ssn",code,
					"login_id",u.getCode(),
					"city_id",city.getCityId(),
					"bank_cd",bank.getCode(), 
					"card_no",bankAccount,
					"file1",FileUtil.upload(file1,file1.length()>3*1024*1024),
					"file2",file2!=null?FileUtil.upload(file2,file2!=null && file2.length()>3*1024*102):"",
					"sign","bank_cd,card_no,city_id,login_id,mchnt_cd,mchnt_txn_ssn"
				)
			);

			if(res.isSuccess()){			
				new BankCard()
					.setCode(code)
					.setUserId(u.getId())
					.setBankCode(bank.getCode())
					.setBankName(bank.getName())
					.setAccountName(u.getRealName())
					.setBankAccount(bankAccount)
					.setMobile(u.getMobile())
					.setProvince(city.getProvince())
					.setCity(city.getCity())
					.setCreateTime(new Date())
					.setStatus("process")
					.setSummary("已提交审核")
					.save();
				renderJson(Json.ok("操作成功！"));
			}else{
				renderJson(Json.error(res.getErrorMsg()));
			}
		}else{
			renderJson(Json.error("卡号已存在！"));
		}
	}
}
 